package models

import (
	"time"
	"github.com/astaxie/beego/validation"
	"errors"
	"github.com/astaxie/beego/orm"
)
type Email struct {
	Id int64 `orm:"auto"`
	UserName string `orm:"size(100)" `
	NickName string `orm:"size(100)" `
	Password string `orm:"size(100)" `
	HostName string `orm:"size(100)" `
	Port int `orm:"default(465)"`
	IsSsl int `orm:"default(0)"`
	Created time.Time `orm:"auto_now_add;type(datetime)"`
	Updated time.Time `orm:"auto_now;type(datetime)"`
}

type ReqEmail struct {
	UserName string
	NickName string
	Password string
	HostName string
	Port int
	IsSsl int
}

type SendEmail struct {
	To string
	Subject string
	Body string
}

/**
添加
 */
func (this *Email) AddEmail() (int64, error) {
	if err := this.valid("add"); err != nil {
		return 0,err
	}
	if this.Port == 0 {
		this.Port = 465
	}
	o := orm.NewOrm()
	return o.Insert(this)
}

/**
获取单个
 */
func (this *Email) GetEmail(id int64) (interface{}, error) {
	o := orm.NewOrm()
	var maps []orm.Params
	num,err := o.Raw("SELECT id,user_name,nick_name,host_name,port,is_ssl FROM email WHERE id = ?",id).Values(&maps)
	if err != nil {
		return nil,err
	}
	if num != 1 {
		return nil,errors.New("不存在此ID数据")
	}
	return maps[0],nil

}

/**
获取单个
 */
func (this *Email) GetInfo() error {
	o := orm.NewOrm()
	return o.Read(this)
}


/**
获取全部
 */
func (this *Email) GetAllEmail() (interface{}, error) {
	o := orm.NewOrm()
	var maps []orm.Params
	num,err := o.Raw("SELECT id,user_name,nick_name,host_name,port,is_ssl FROM email").Values(&maps)
	if err != nil {
		return nil,err
	}
	if num <= 0 {
		return nil,errors.New("无数据")
	}
	return maps,nil

}

/**
添加
 */
func (this *Email) UpdateEmail() (interface{}, error) {
	if err := this.valid("update"); err != nil {
		return 0,err
	}
	if this.Port == 0 {
		this.Port = 465
	}
	o := orm.NewOrm()
	_,err := o.Update(this,"UserName","NickName","Password","HostName","Port","IsSsl","Updated")
	if err != nil {
		return "",err
	}
	return this.GetEmail(this.Id)
}

func (this *Email) DeleteEmail() error {
	o := orm.NewOrm()
	 _,err := o.Delete(this)
	return err
}

/**
验证数据
 */
func (this *Email) valid(str string) error {
	valid := validation.Validation{}

	if v := valid.Required(this.UserName,"用户名"); !v.Ok {
		return errors.New(v.Error.Key + v.Error.Message)
	}
	if v := valid.Email(this.UserName,"用户名"); !v.Ok {
		return errors.New(v.Error.Key + v.Error.Message)
	}
	if v := valid.Required(this.NickName,"昵称"); !v.Ok {
		return errors.New(v.Error.Key + v.Error.Message)
	}
	if v := valid.Required(this.Password,"邮箱密码"); !v.Ok {
		return errors.New(v.Error.Key + v.Error.Message)
	}
	if v := valid.Required(this.HostName,"邮件服务器"); !v.Ok {
		return errors.New(v.Error.Key + v.Error.Message)
	}
	//if v := valid.Required(this.Port,"邮件服务器端口"); !v.Ok {
	//	return errors.New(v.Error.Key + v.Error.Message)
	//}

	return nil
}






